package com.ssm.security;

import com.ssm.service.dao.impl.JedisClientClusterImpl;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;

/**
 * Created by asd73 on 2017/8/3.
 */
public class UserStatus2Redis {

    @Value("${USER_LOGIN_NUM_LIMIT}")
    private Long USER_LOGIN_NUM_LIMIT;

    @Value("${USER_REDIS_TOKEN_EXPIRE_TIME}")
    private Integer USER_REDIS_TOKEN_EXPIRE_TIME;

    private JedisClientClusterImpl jedisClientClusterImpl;

    public JedisClientClusterImpl getJedisClientClusterImpl() {
        return jedisClientClusterImpl;
    }

    public void setJedisClientClusterImpl(JedisClientClusterImpl jedisClientClusterImpl) {
        this.jedisClientClusterImpl = jedisClientClusterImpl;
    }

    /**
     * 1.用户是否存在redis中
     * 2.查询用户是否超出登录数量限制
     *  超出了则删除最早登录的那个用户相关user-uuid信息（也就是踢出）同时要删除uuid-token
     * 3.其中的还要判断当前用户的登录数量-所设定的登录数量是否>0
     *  为了防止：当前设定的登陆数量为10人，新设定的登陆数量为5人，
     *  如果不进行10-5>0判断，则同时登陆数量会一直为10人
     * 4.将用户登录信息存入redis
     * @param username
     * @param r_id
     * @param JWT
     * @throws IOException
     */
    public void saveUser2Redis(String username,String r_id,String JWT) throws IOException {
        if (jedisClientClusterImpl.exists(username)){
            Long num = jedisClientClusterImpl.llen(username);
            if (num>= USER_LOGIN_NUM_LIMIT){
                if (num-USER_LOGIN_NUM_LIMIT>0){
                    for (int i = 0; i<num-USER_LOGIN_NUM_LIMIT;i++){
                        jedisClientClusterImpl.del(jedisClientClusterImpl.lpop(username));
                    }
                }
                jedisClientClusterImpl.del(jedisClientClusterImpl.lpop(username));
            }
        }
        try {
            jedisClientClusterImpl.rpush(username,r_id);
            jedisClientClusterImpl.set(r_id,JWT);
            jedisClientClusterImpl.expire(r_id,USER_REDIS_TOKEN_EXPIRE_TIME);
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * 删除用户的登陆信息username-r_id r_id-token
     * @param username
     * @param r_id
     */
    public void deleteUserStatus(String username,String r_id){
        System.out.println(jedisClientClusterImpl.lrem(username,r_id));
        System.out.println(jedisClientClusterImpl.del(r_id));
    }

    /**
     * 刷新用户token后需要刷新redis中对应的r_id-token
     * @param r_id
     * @param JWT
     */
    public void refreshUserStatus(String r_id,String JWT){
        System.out.println(jedisClientClusterImpl.set(r_id,JWT));
        jedisClientClusterImpl.expire(r_id,USER_REDIS_TOKEN_EXPIRE_TIME);
    }

    /**
     * 根据r_id查找redis中对应的token
     * @param r_id
     * @return
     */
    public String getUsertoken(String r_id){
        return jedisClientClusterImpl.get(r_id);
    }


}
